package com.zhanghe.study.netty.codec;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

/**
 * 客户端
 * @author zh
 * @date 2020/12/2 11:32
 */
public class Client {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group) // 线程组
                    .channel(NioSocketChannel.class) // 客户端NioSocketChannel通道
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 客户端处理器
                            // ProtobufEncoder是proto编码器
                            socketChannel.pipeline()
                                    .addLast("encoder",new ProtobufEncoder())
                                    .addLast(new ClientHandler());
                        }
                    });
            System.out.println("客户端启动");
            ChannelFuture future = bootstrap.connect("127.0.0.1",8765).sync();

            // 阻塞  防止关闭  只有关闭事件触发才会执行
            future.channel().closeFuture().sync();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }


    }
}
